package com.zxf.appliction.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zxf.appliction.domain.Messages;
import com.zxf.appliction.domain.Params;
import com.zxf.appliction.domain.Users;
import com.zxf.appliction.service.UserService;
import com.zxf.appliction.util.DateJsonValueProcessor;

@Controller
@RequestMapping(value = "/userRedis")
public class UserRedisController {

	@Autowired
	private UserService userService;

	
	private static Logger logger = Logger.getLogger(UserRedisController.class);

	@RequestMapping(value = { "/add", "/add.html" }, method = { RequestMethod.GET })
	public ModelAndView add(HttpServletRequest request, HttpServletResponse response) {
		// return toView("add", map);
		return null;
	}

	@RequestMapping(value = { "/saveuser" }, method = { RequestMethod.POST })
	public void saveuser(Users user, HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		Map<String, Object> responseMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		UUID.randomUUID();
		// user.setUserid(UUID.randomUUID().toString());
		user.setUserid(5);

		user.setSignup(new Date());

		userService.saveUser(user);
		Boolean flag = true;
		Users users = userService.getuser(user.getUsername().toLowerCase());
		logger.info(obj.toString());
		// logger.info("json2:"+json2);
		if (null != users && null != users.getUsername() && "".equals(users.getUsername())) {
			responseMap.put("method", "Create");
			responseMap.put("success", "true");
			responseMap.put("info", "新增成功！");
			response.setContentType("text/html;charset=UTF-8");

		} else {
			responseMap.put("method", "Create");
			responseMap.put("success", "false");
			responseMap.put("info", "新增失败！");
			response.setContentType("text/html;charset=UTF-8");

		}

	}

	// 用户登录
	@RequestMapping("/userlogin")
	public @ResponseBody JSONObject userlogin(Users users, HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		HttpSession session = request.getSession();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		Users users2;
		// 得到生成的验证码
		String strCode = (String) session.getAttribute("randomCode");
		logger.info("验证码:" + strCode);
		// 定义一个msg变量，可用于存放错误信息，然后传到前台
		// 用于告诉前台时候登录成功
		boolean successe = false;
		if (!users.getCheckCode().toLowerCase().equals(strCode.toLowerCase())) {
			obj.put("success", false);
			obj.put("message", "验证码错误！");
			return obj;

		}

		users2 = userService.getuser("");
		if (null != users2) {
			obj.put("users", users2);
			obj.put("success", true);

		} else {
			obj.put("success", false);
			obj.put("message", "用户名或者密码错误！");

		}

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	@RequestMapping(value = { "/userlist" })
	public @ResponseBody JSONObject userlist(Params params, String page, String limit, String start, Users users,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		// StringBuffer toJson=new StringBuffer();//用来放json数据
		JSONArray js = new JSONArray();
		// 页码
		int pageno = Integer.parseInt(page);
		// 每页数量
		int pageSize2 = Integer.parseInt(limit);
		List userlist = userService.getRedisUserList(pageno, pageSize2);
		int totle = userService.getRedistotle("users");
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		obj.put("data", js.fromObject(userlist, jsonConfig));
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("success", true);

		// json格式化后输出
		logger.info(obj.toString());
		return obj;

	}

	@RequestMapping(value = { "/{id:\\d+}/query", "/{id:\\d+}/query.html" }, method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView queryMember(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.info(id);
		Users users = this.userService.getId(Integer.parseInt(id));
		if (null != users) {
			map.put("message", "查询Id=" + id + "的用户名为:" + users.getUsername());
		} else {
			map.put("message", "没有查询到与Id=" + id + "相关的数据");
		}
		return null;
	}

	@RequestMapping(value = { "/{id:\\d+}/delete", "/{id:\\d+}/delete.html" }, method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView deleteMember(HttpServletRequest request, HttpServletResponse response,
			@PathVariable("id") String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			this.userService.delete(Integer.parseInt(id));
			map.put("message", "删除Id为" + id + "的用户成功.");
		} catch (Exception e) {
			logger.info("删除Id为" + id + "的用户失败, "+e);
		}
		// return toView("member/message", map);
		return null;
	}

	@RequestMapping(value = { "/savemessage" }, method = { RequestMethod.POST })
	public void savemessage(Messages message, HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		Map<String, Object> responseMap = new HashMap<String, Object>();
		message.setId("1");
		message.setPosted(new Date());
		message.setUid("5");
		message.setLoginame("34567");
		userService.saveMessage(message);
		Boolean flag = true;
		Messages messages = userService.getmessage(message.getId().toLowerCase());
		logger.info("Message:" + obj.toString());
		if (null != messages && null != messages.getId() && "".equals(messages.getId())) {
			responseMap.put("method", "Create");
			responseMap.put("success", "true");
			responseMap.put("info", "新增成功！");
			response.setContentType("text/html;charset=UTF-8");

		} else {
			responseMap.put("method", "Create");
			responseMap.put("success", "false");
			responseMap.put("info", "新增失败！");
			response.setContentType("text/html;charset=UTF-8");

		}

	}

	@RequestMapping(value = { "/messagelist" })
	public @ResponseBody JSONObject messagelist(String page, String limit, String start, Users users,
			HttpServletRequest request, HttpServletResponse response) {
		JSONObject obj = new JSONObject();
		JSONArray js = new JSONArray();
		// 页码
		int pageno = Integer.parseInt(page);
		// 每页数量
		int pageSize = Integer.parseInt(limit);

		List messagelist = userService.getRedisMessagesList(pageno, pageSize);
		int totle = userService.getRedistotle("message");
		JsonConfig jsonConfig = new JsonConfig();
		// 实体类里面存在的时间类型为Timestamp，之前放的Date，解析格式还是原来那样，后来换成这个好使。
		jsonConfig.registerJsonValueProcessor(java.util.Date.class, new DateJsonValueProcessor("yyyy-MM-dd"));
		obj.put("data", js.fromObject(messagelist, jsonConfig));
		obj.put("total", totle); // 统计数量，这里写死10条
		obj.put("success", true);

		// json格式化后输出
		logger.info("messagelist:" + obj.toString());
		return obj;

	}

}
